package com.qdsg.ysg.doctor.nurse.activity;

import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.ui.adapter.HistoryOrderAdapter;
import com.qdsg.ysg.doctor.ui.dialog.SelectTimeDialog;
import com.qdsg.ysg.doctor.util.SoftKeyboardUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.BaseStringResponse;
import com.rest.response.DocOrderListVO;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.UtilList;

/**
 * @time 2021/4/12 15:12
 */
public class AtyHistoryOrderList extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.edt_search)
    EditText edtSearch;
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    @BindView(R.id.tv_sure_num)
    TextView tvSureNum;
    @BindView(R.id.ll_end)
    LinearLayout llEnd;
    @BindView(R.id.tv_cancel_num)
    TextView tvCancelNum;
    @BindView(R.id.ll_cancel)
    LinearLayout llCancel;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.rv_history)
    RecyclerView rvHistory;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.cl_empty)
    ConstraintLayout clEmpty;

    private String keyWord, type, startDate = "", endDate = "";
    int current = 1, totalPage;
    Boolean isLoadMore = true;//能不能继续加载更多

    List<DocOrderListVO.AcceptOrderList> mList = new ArrayList<>();
    private HistoryOrderAdapter historyOrderAdapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_history_order_list;
    }

    @Override
    protected void initViews() {
        tvTitle.setText( "历史订单" );
        LinearLayoutManager manager = new LinearLayoutManager( mContext );
        manager.setOrientation( LinearLayoutManager.VERTICAL );
        rvHistory.setLayoutManager( manager );
        historyOrderAdapter = new HistoryOrderAdapter( mContext, mList );
        rvHistory.setAdapter( historyOrderAdapter );
//        refreshLayout.setPrimaryColors( 0xffffffff, 0xff5481FA );
        refreshLayout.setEnableLoadMore( true );

        refreshLayout.setOnRefreshListener( refreshlayout -> {
            refreshLayout.finishRefresh();
            refreshLayout.setNoMoreData( false );//复原状态
            current = 1;
            getHisOrderList();

        } );
        //加载更多
        refreshLayout.setOnLoadMoreListener( refreshLayout -> {
            LogUtil.e( "总数---" + totalPage );
            if (current >= totalPage) {
                refreshLayout.finishLoadMore();
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                //refreshLayout.setNoMoreData(false);

                ToastUtil.showToast( mContext, "数据全部加载完毕" );
            } else {
                getHisOrderListMore();

            }
        } );
        edtSearch.setOnEditorActionListener( (v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 按下完成按钮，这里和上面imeOptions对应
                keyWord = edtSearch.getText().toString().trim();
                refreshLayout.finishRefresh();
                refreshLayout.setNoMoreData( false );//复原状态
                current = 1;
                getHisOrderList();
                SoftKeyboardUtil.hideSoftKeyboard( mContext );
            }
            return false;
        } );


    }


    @Override
    protected void initData() {
        getOrderDoneCount();
        getCancelCount();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getHisOrderList();
    }

    @OnClick({R.id.ll_time, R.id.ll_end, R.id.ll_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_time:
                showSelectTimeDialog();
                break;
            case R.id.ll_end:
                type = "0";
                refreshLayout.finishRefresh();
                refreshLayout.setNoMoreData( false );//复原状态
                current = 1;
                getHisOrderList();
                break;
            case R.id.ll_cancel:
                type = "4";
                refreshLayout.finishRefresh();
                refreshLayout.setNoMoreData( false );//复原状态
                current = 1;
                getHisOrderList();
                break;
        }
    }


    private void getHisOrderList() {
        Map<String, Object> map = new HashMap<>();
        map.put( "current", current + "" );
        map.put( "type", type );//状态0已完成4已取消
        map.put( "keyWord", keyWord );
        map.put( "startDate", startDate );
        map.put( "endDate", endDate );
        map.put( "size", "10" );
        RestProxy.getInstance().getHisOrderList( map, new Observer<DocOrderListVO>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(DocOrderListVO orderListVO) {
                try {
                    totalPage = Integer.parseInt( orderListVO.data.pages );
                    List<DocOrderListVO.AcceptOrderList> list = orderListVO.data.records;
                    if (!UtilList.isEmpty( list )) {
                        refreshLayout.setVisibility( View.VISIBLE );
                        clEmpty.setVisibility( View.GONE );
                        mList.clear();
                        mList.addAll( list );
                        historyOrderAdapter.notifyDataSetChanged();
                    } else {
                        refreshLayout.setVisibility( View.GONE );
                        clEmpty.setVisibility( View.VISIBLE );
                    }


                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( mContext, e );
                refreshLayout.finishRefresh( false );
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh( true );
            }
        } );
    }


    private void getHisOrderListMore() {
        current += 1;
        Map<String, Object> map = new HashMap<>();
        map.put( "current", current + "" );
        map.put( "size", "10" );
        RestProxy.getInstance().getHisOrderList( map, new Observer<DocOrderListVO>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(DocOrderListVO orderListVO) {
                List<DocOrderListVO.AcceptOrderList> list = orderListVO.data.records;
                if (!UtilList.isEmpty( list )) {
                    mList.addAll( list );
                    historyOrderAdapter.notifyDataSetChanged();
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( mContext, e );
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onComplete() {
                refreshLayout.finishLoadMore();
            }
        } );
    }


    private void getOrderDoneCount() {
        Map<String, Object> map = new HashMap<>();
        map.put( "type", type );//状态0已完成4已取消
        map.put( "keyWord", keyWord );
        map.put( "startDate", startDate );
        map.put( "endDate", endDate );
        RestProxy.getInstance().getOrderDoneCount( map, new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseStringResponse baseResponse) {
                try {
                    tvSureNum.setText( baseResponse.data );
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( mContext, e );
            }

            @Override
            public void onComplete() {

            }
        } );
    }

    private void getCancelCount() {
        Map<String, Object> map = new HashMap<>();
        map.put( "type", type );//状态0已完成4已取消
        map.put( "keyWord", keyWord );
        map.put( "startDate", startDate );
        map.put( "endDate", endDate );
        RestProxy.getInstance().getCancelCount( map, new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseStringResponse baseResponse) {
                try {
                    tvCancelNum.setText( baseResponse.data );
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( mContext, e );
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    private void initTimePicker() {//Dialog 模式下，在底部弹出

    }

    /**
     * 时间选择器
     */
    private void showSelectTimeDialog() {
        SelectTimeDialog mTimeDialogFragment = SelectTimeDialog.newInstance();
        if (!mTimeDialogFragment.isAdded() && !mTimeDialogFragment.isShowing()) {
            mTimeDialogFragment.show( getSupportFragmentManager(), "mTimeDialogFragment" );
        }
        mTimeDialogFragment.setmListener( new SelectTimeDialog.OnItemClickListener() {
            @Override
            public void onConfirm(String mStartDate, String mEndDate) {
                LogUtil.e( "时间页面--" + startDate + "-----" + endDate );
                startDate = mStartDate;
                endDate = mEndDate;
                refreshLayout.finishRefresh();
                refreshLayout.setNoMoreData( false );//复原状态
                current = 1;
                getHisOrderList();
                mTimeDialogFragment.dismiss();
            }

            @Override
            public void onCancel() {

            }


        } );

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


}

